﻿<%@ WebHandler Language="C#" Class="YPContainerDispatchFormHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using DatabaseAccess.DBUtility;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;

//Description:批量、单次派工弹窗页面处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-01-13

public class YPContainerDispatchFormHandler : IHttpHandler, IRequiresSessionState
{
    uLMSCommonIBusiness uMESCommonbusiness = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSDispatchIBusiness uMESDispatchbusiness = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    uLMSCommissioningIBusiness m_commissioning = uMESBusinessFactory.instance.GetuLMSCommissioning();
    uLMSContainerShipIBusiness m_ontainerShipObject = uMESBusinessFactory.instance.GetuLMSContainerShipObject();
    uLMSBathResMonitorBusiness bathResMonitorBusiness = new uLMSBathResMonitorBusiness();
    uLMSWorkReportIBusiness m_ReportBusiness = uMESBusinessFactory.instance.GetuLMSWorkReportObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetInitData"://初始化页面
                    GetInitData(context);
                    break;
                case "GetOperator"://获取操作工
                    GetOperator(context);
                    break;
                case "GetResource"://获取设备
                    GetResource(context);
                    break;
                case "GetWorkerDispatchAndReportInfo"://获取员工派工与报工信息
                    GetWorkerDispatchAndReportInfo(context);
                    break;
                case "SaveSingleDispatchData"://保存单次派工信息
                    SaveSingleDispatchData(context);
                    break;
                case "SaveBatchDispatchData"://保存批量派工信息
                    SaveBatchDispatchData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "出错了：" + e.Message, Result = false }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 获取页面初始化数据
    /// </summary>
    /// <param name="context"></param>
    public void GetInitData(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        DataTable dtContainers = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["containers"].ToString());
        if (m_UserInfo == null || dtContainers == null || dtContainers.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "缓存过期，请刷新后再试", Result = false }));
            return;
        }
        DataSet dtSet = new DataSet();
        //获取零件序号列表
        DataTable childDt = uMESCommonbusiness.GetContainerInfoByPerContianerID(dtContainers.Rows[0]["ContainerID"].ToString());
        childDt.TableName = "childDt";
        dtSet.Tables.Add(childDt);
        //获取班组下拉数据
        DataTable dt_team = uMESCommonbusiness.GetTeam(m_UserInfo.WorkCenterID);
        DataRow drteam = dt_team.NewRow();
        drteam["TEAMID"] = "";
        drteam["TEAMNAME"] = "请选择";
        dt_team.Rows.InsertAt(drteam, 0);//插入到第一行
        drteam = dt_team.NewRow();
        drteam["TEAMID"] = "0";
        drteam["TEAMNAME"] = "其他";
        dt_team.Rows.Add(drteam);
        string strAttributes = uMESCommonbusiness.GetEnterpriseAttributes("工区长角色");
        if (strAttributes == "")
        {
            strAttributes = "DispatchTFW";
        }
        if (!m_UserInfo.Roles.Contains(strAttributes))
        {
            DataRow drs = dt_team.Select(string.Format("TeamID = '{0}'", m_UserInfo.TeamID)).FirstOrDefault();
            dt_team.Rows[0].ItemArray = drs.ItemArray;//将该员工对应的班组放在第一个并默认选中
            dt_team.Rows.Remove(drs);
            string strValue_ = uMESCommonbusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "多人派工"); //获取工厂是否多人派工 燃烧不修改不可以派给其他班组
            if (strValue_ == "是")
            {
                int len = dt_team.Rows.Count - 1;
                for (int i = 0; i < len; i++)
                {
                    dt_team.Rows.RemoveAt(1);//删除第一条以外的所有行，确保只有一个班组
                }
            }
        }
        dt_team.TableName = "dtTeam";
        dtSet.Tables.Add(dt_team);
        //获取当前工序后的所有工序
        string strSequence = dtContainers.Rows[0]["Sequence"].ToString();
        string strWorkflowid = dtContainers.Rows[0]["WorkflowID"].ToString();
        int intWIPQty = Convert.ToInt32(dtContainers.Rows[0]["WipQty"].ToString());
        string strContainerIDs = string.Empty;
        DataTable workStepDT = GetWorkflowDT(ref strContainerIDs, m_UserInfo, dtContainers);
        //增加对不加工工序的筛选 add by zhangrj 2022-11-04
        ExcuteEntity exuteEntity = new ExcuteEntity("containerstepnoship", ExcuteEntity.ExcuteTypeEnum.selectAll);
        exuteEntity.WhereFileds = new List<FieldEntity>() {new FieldEntity("containerid", dtContainers.Rows[0]["ContainerID"].ToString(), FieldEntity.FieldTypeEnum.Str),
                                                                     new FieldEntity("isuse", 0, FieldEntity.FieldTypeEnum.Numer),
                                                                     new FieldEntity("noship", 2, FieldEntity.FieldTypeEnum.Numer)};
        DataTable dtNoShip = DatabaseHelper.QueryDataByEntity(exuteEntity);
        foreach (DataRow drNs in dtNoShip.Rows)
        {
            //存在该工序不加工，则移除
            DataRow drw = workStepDT.Select("WorkflowStepID='" + drNs["WorkflowStepID"].ToString() + "'").FirstOrDefault();
            if (drw != null)
            {
                workStepDT.Rows.Remove(drw);
                workStepDT.AcceptChanges();
            }
        }
        Dictionary<string, string> isPara = new Dictionary<string, string>();
        isPara["ContainerID"] = strContainerIDs;
        isPara["WorkCenterID"] = m_UserInfo.WorkCenterID;
        isPara["FactoryID"] = m_UserInfo.FactoryID;
        isPara["Sequence"] = strSequence;
        DataTable workCenterDispach = uMESDispatchbusiness.GetWorkCenterORShipInfo(isPara, 0);
        DataTable shipInfo = uMESDispatchbusiness.GetWorkCenterORShipInfo(isPara, 1);
        string str_ContainerID = "";
        if (dtContainers.Rows[0]["ContainerType"].ToString() == "7")
        {
            foreach (DataRow item in dtContainers.Rows)
            {
                if (str_ContainerID.Length > 0)
                {
                    str_ContainerID += " OR ";
                }
                str_ContainerID += " CC.CONTAINERID = '" + item["ContainerID"] + "'";
            }
        }
        else
        {
            str_ContainerID = " CC.CONTAINERID ='" + dtContainers.Rows[0]["ContainerID"].ToString() + "'";
        }
        DataTable dt_commission = m_commissioning.GetCommissionProcess(ref str_ContainerID); //外委工序表
        if (shipInfo.Rows.Count > 0) //只显示转工的工序
        {
            foreach (DataRow dt in workStepDT.Rows)
            {
                if (shipInfo.Rows[0]["STEPTYPE"].ToString() == "2")
                { //转工的子工艺
                    continue;
                }
                if (int.Parse(shipInfo.Compute("COUNT(WORKFLOWSTEPID)", String.Format("WORKFLOWSTEPID='{0}'", dt["WORKFLOWSTEPID"].ToString())).ToString()) == 0)
                {
                    dt.Delete();
                }
            }
            workStepDT.AcceptChanges();
            ClearNoUseWorkflowStepID(ref workStepDT, dt_commission, new DataTable(), new DataTable(), new DataTable(), new DataTable(), "Dispatch");
        }
        else
        {
            DataTable dt_ship = m_ontainerShipObject.GetShipWorkflowStepIDs(str_ContainerID); //临时转工工序表
            DataTable newdt = uMESCommonbusiness.GetContainerInfobyContainerName(dtContainers.Rows[0]["ContainerName"].ToString()); //根据批次号获取批次的factoryID
            DataTable dt_ControlCodeAndLastCheck = uMESCommonbusiness.GetWorkFlowStepsWithSpceControlCodeAndCheckStep(strWorkflowid, newdt.Rows[0]["FACTORYID"].ToString()); //固定外委或固定转工或检验工序表
            //增加临时取消自动转工或外委逻辑
            DataTable dt_ControlCodeAndLastCheck2 = dt_ControlCodeAndLastCheck.Clone();
            Dictionary<string, string> temPara = new Dictionary<string, string>();
            temPara["ContainerIDsOr"] = str_ContainerID.Replace("CC", "csn");
            foreach (DataRow shipCommison in dt_ControlCodeAndLastCheck.Rows)
            {
                temPara["CheckedWorkflowStepID"] = shipCommison["WorkflowStepID"].ToString();
                if (m_ontainerShipObject.GetCancleAutoShipOrComission(temPara).Rows.Count == 0)
                {
                    dt_ControlCodeAndLastCheck2.ImportRow(shipCommison);
                }
            }
            workStepDT.AcceptChanges();
            ClearNoUseWorkflowStepID(ref workStepDT, dt_commission, dt_ship, new DataTable(), dt_ControlCodeAndLastCheck2, new DataTable(), "Dispatch");
        }
        if (workCenterDispach.Rows.Count > 0) //只显示工区协作的工序           
        {
            workStepDT.AcceptChanges();
            foreach (DataRow item in workStepDT.Rows)
            {
                if (int.Parse(workCenterDispach.Compute("COUNT(WORKFLOWSTEPID)", string.Format("WORKFLOWSTEPID='{0}'", item["WORKFLOWSTEPID"].ToString())).ToString()) == 0)
                {
                    if (workCenterDispach.Rows[0]["workcenterid"].ToString() == m_UserInfo.WorkCenterID)
                    { //如果是原来的工区 ’add Wangjh 2017-7-11
                        continue;
                    }
                    else if (workCenterDispach.Rows[0]["Toworkcenterid"].ToString() == m_UserInfo.WorkCenterID)
                    { //如果是协作的工区
                        item.Delete();
                        continue;
                    }
                }
                if (workCenterDispach.Rows[0]["workcenterid"].ToString() == m_UserInfo.WorkCenterID)
                { //如果是原来的工区 ’add Wangjh 2017-7-11
                    item.Delete(); //这里隐藏存在工区协作的
                }
            }
        }
        workStepDT.AcceptChanges();
        workStepDT.TableName = "dtWorkStep";
        dtSet.Tables.Add(workStepDT);
        //优先级
        DataTable natdt = uMESCommonbusiness.GetNaturalNumberDatatable(uLMS_CommonFunction.GetNaturalNumberSql(1, 9));
        natdt.TableName = "natdt";
        dtSet.Tables.Add(natdt);
        uMESProcessResult result = new uMESProcessResult() { Message = "获取成功", Result = true, DBDataSet = dtSet };
        if (m_UserInfo.Factory.Contains("工装工具"))
        {
            result.ReturnData = "工装工具";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工艺工序信息
    /// </summary>
    /// <param name="strContainerIDs"></param>
    /// <param name="userInfo"></param>
    /// <param name="containerInfo"></param>
    /// <param name="containerIndex"></param>
    /// <returns></returns>
    private DataTable GetWorkflowDT(ref string strContainerIDs, CurrentUserInfo userInfo, DataTable containerInfo)
    {
        bool notDelete = false;
        if (strContainerIDs == "strnull")
        {
            notDelete = true;
            strContainerIDs = "";
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("WorkflowID", containerInfo.Rows[0]["WorkflowID"].ToString());
        para.Add("Sequence", containerInfo.Rows[0]["Sequence"].ToString());
        string strSelectvalue = uMESCommonbusiness.GetFatoryAttributes(userInfo.FactoryID, "工序关联工区班组"); //获取工厂报工是否工序工区派工
        if (strSelectvalue == "是")
        {
            para.Add("StepDispatch", "");
            para.Add("ContainerID", containerInfo.Rows[0]["ContainerID"].ToString());
            para.Add("TeamID", userInfo.TeamID);
        }
        DataTable dtWorkflow = uMESCommonbusiness.GetWorkFlowStepsWithoutSelf(para); //获取当前工序及以后的所有工序
        foreach (DataRow item in containerInfo.Rows)
        {
            strContainerIDs = String.Format("{0},'{1}'", strContainerIDs, item["ContainerID"].ToString());
        }
        if (strContainerIDs.Length > 0)
        {
            strContainerIDs = strContainerIDs.Substring(1);
        }
        //处理以及完工的工序就不再显示
        DataTable IsCompleted_dt = uMESDispatchbusiness.GetIsCompletedStep(strContainerIDs, containerInfo.Rows[0]["WorkflowID"].ToString());
        if (IsCompleted_dt.Rows.Count > 0)
        {
            foreach (DataRow cr in IsCompleted_dt.Rows)
            {
                foreach (DataRow wf in dtWorkflow.Rows)
                {
                    if (wf["WORKFLOWSTEPID"].ToString() == cr["WORKFLOWSTEPID"].ToString())
                    {
                        wf.Delete();
                        break;
                    }
                }
                dtWorkflow.AcceptChanges();
            }
        }
        para.Clear();
        para.Add("WorkflowID", containerInfo.Rows[0]["WorkflowID"].ToString());
        para.Add("Sequence", containerInfo.Rows[0]["Sequence"].ToString());
        para.Add("ContainerIDs", strContainerIDs);
        DataTable dtStepDispatch = uMESDispatchbusiness.GetStepDispatchSpecList(para); //获取批次当前序及之后已经派工的信息
        dtWorkflow.Columns.Add("CanDispatchQty"); //在所有工序表中添加两行 可派数以及已经派工的工人ID
        dtWorkflow.Columns.Add("DispatchWorkers");
        DataTable dtworker = uMESDispatchbusiness.GetDispatchWorkerList(para);//根据containerid获取该批次已经派工的
        for (int i = 0; i < dtWorkflow.Rows.Count; i++)
        {
            DataRow drStep = dtWorkflow.Rows[i];
            string objQty = dtStepDispatch.Compute("SUM(DISQTY)", String.Format("WORKFLOWSTEPID='{0}'", drStep["WORKFLOWSTEPID"])).ToString();
            if (string.IsNullOrWhiteSpace(objQty))
            {
                drStep["CanDispatchQty"] = containerInfo.Rows[0]["WipQty"];
                continue;
            }
            if (Convert.ToInt32(containerInfo.Rows[0]["WipQty"].ToString()) > Convert.ToInt32(objQty))
            {
                int intCanQty = Convert.ToInt32(containerInfo.Rows[0]["WipQty"].ToString()) - Convert.ToInt32(objQty);
                drStep["CanDispatchQty"] = intCanQty;
            }
            else
            {
                if (!notDelete)
                {
                    drStep.Delete();
                    continue;
                }
            }
            DataRow[] drs = dtworker.Select(String.Format("WORKFLOWSTEPID='{0}'", drStep["WORKFLOWSTEPID"]));
            string strDispatchWorkers = "";
            foreach (DataRow dr in drs)
            {
                if (dr["CSD_WORKERID"] != null)
                {
                    strDispatchWorkers = String.Format("{0},{1}", strDispatchWorkers, dr["CSD_WORKERID"]); //单人派工
                }
                else
                {
                    strDispatchWorkers = String.Format("{0},{1}", strDispatchWorkers, dr["CSDT_WORKERID"]); //多人派工
                }
            }
            drStep["DispatchWorkers"] = strDispatchWorkers;
        }
        dtWorkflow.AcceptChanges();
        return dtWorkflow;
    }

    /// <summary>
    /// 派工、外委、工区协助等工序排除
    /// </summary>
    /// <param name="workStepDT"></param>
    /// <param name="dt_commission"></param>
    /// <param name="dt_ship"></param>
    /// <param name="dt_workCenter"></param>
    /// <param name="dt_ControlCodeAndLastCheck"></param>
    /// <param name="dt_Dispatched"></param>
    /// <param name="key"></param>
    private void ClearNoUseWorkflowStepID(ref DataTable workStepDT, DataTable dt_commission, DataTable dt_ship, DataTable dt_workCenter, DataTable dt_ControlCodeAndLastCheck, DataTable dt_Dispatched, string key)
    {
        bool ishidden = false;
        foreach (DataRow dt in workStepDT.Rows)
        {
            if (key != "Dispatch")
            {
                if (dt_Dispatched.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_Dispatched.Rows)
                    {
                        if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                        {
                            dt.Delete();
                            ishidden = true;
                            break;
                        }
                    }
                }
                if (ishidden)
                {
                    continue;
                }
            }
            if (key != "Commission")
            {
                if (dt_commission.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_commission.Rows)
                    {
                        if (Convert.ToInt32(dt["Sequence"].ToString()) >= Convert.ToInt32(row["FIRSTSEQUENCE"].ToString()) && Convert.ToInt32(dt["Sequence"]) < Convert.ToInt32(row["LASTSEQUENCE"].ToString()))
                        {
                            if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                            {
                                dt.Delete();
                            }
                        }
                    }
                }
            }
            ishidden = false;
            if (key != "Ship")
            {
                if (dt_ship.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_ship.Rows)
                    {
                        if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                        {
                            dt.Delete();
                            ishidden = true;
                            break;
                        }
                    }
                }
                if (ishidden)
                {
                    continue;
                }
            }
            ishidden = false;
            if (key != "workCenter")
            {
                if (dt_workCenter.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_workCenter.Rows)
                    {
                        if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                        {
                            dt.Delete();
                            ishidden = true;
                            break;
                        }
                    }
                }
                if (ishidden)
                {
                    continue;
                }
            }
            if (dt_ControlCodeAndLastCheck.Rows.Count > 0)
            {
                foreach (DataRow row in dt_ControlCodeAndLastCheck.Rows)
                {
                    if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                    {
                        dt.Delete();
                        break;
                    }
                }
            }
        }
    }

    /// <summary>
    /// 选择班组后，获取操作工
    /// update:wangjh 20220302 优化增加人员设备查询
    /// </summary>
    /// <param name="context"></param>
    public void GetOperator(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string strSelectValue = context.Request.Form["teamID"].ToString();
        DataTable dt = new DataTable();
        Dictionary<string, string> para = new Dictionary<string, string>();
        if (strSelectValue == "0")
        {
            string strAttributes = uMESCommonbusiness.GetEnterpriseAttributes("工区长角色");

            para.Add("RoleName", strAttributes);
            para.Add("WorkCenterID", m_UserInfo.WorkCenterID);
            para.Add("FactoryID", m_UserInfo.FactoryID);
            dt = uMESCommonbusiness.GetEmployeeRoles(para);
            dt.Columns.Add("EMPLOYEEID");

            foreach (DataRow item in dt.Rows)
            {
                item["EMPLOYEEID"] = item["CHECKERID"];
            }

            dt.AcceptChanges();
        }
        else
        {
            dt = uMESCommonbusiness.GetEmployeeInfoByTeamId(strSelectValue);
        }

        dt.Columns.Add("RESOURCES");//add:Wangjh 20220302 
        foreach (DataRow item in dt.Rows)
        {
            var temp = uMESCommonbusiness.GetResourceDefByemployeeid(" em.employeeid='" + item["EMPLOYEEID"].ToString() + "'");
            var resources = temp.DefaultView.ToTable(true, "RESNAME", "resourceid");
            item["Resources"] = JsonConvert.SerializeObject(resources);
        }

        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = dt }));
    }
    /// <summary>
    /// 选择员工后,获取设备资源
    /// </summary>
    /// <param name="context"></param>
    public void GetResource(HttpContext context)
    {
        string stremployeeids = context.Request.Form["employeeids"].ToString();
        DataTable dt = uMESCommonbusiness.GetResourceDefByemployeeid(stremployeeids);
        string[] array = new string[2];
        array[0] = "RESNAME";
        array[1] = "resourceid";
        DataTable newdt = dt.DefaultView.ToTable(true, array);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = newdt }));
    }

    /// <summary>
    /// 获取员工派工与报工信息（未完全报工当前序及之后序的记录）
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkerDispatchAndReportInfo(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("PageSize", context.Request.Form["pageSize"].ToString());
        para.Add("CurrentPageIndex", context.Request.Form["pageNumber"].ToString());
        para.Add("WorkerID", context.Request.Form["employeeid"].ToString());
        uMESProcessResult result = uMESDispatchbusiness.GetWorkerDisAndReportInfo(para);
        foreach (DataRow dr in result.DBTable.Rows)
        {
            if (dr.IsNull("WORKERNAME") || dr["WORKERNAME"] == null || string.IsNullOrWhiteSpace(dr["WORKERNAME"].ToString()))
            {
                dr["WORKERNAME"] = dr["WORKERNAME_"];
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, RowCount = result.RowCount, DBTable = result.DBTable }));
    }


    /// <summary>
    /// 保存单个批次派工数据
    /// </summary>
    /// <param name="context"></param>
    private void SaveSingleDispatchData(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "缓存过期，请刷新后再试", Result = false }));
            return;
        }

        //bool isSelfCheck = uMESCommonbusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "自检自分") == "是" ? true : false;//获取分厂属性
        DataTable dtContainers = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["dtContainers"].ToString());//批次列表
        DataTable stepDatas = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["stepDatas"].ToString());//工序列表
        DataTable operatorDatas = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["operatorDatas"].ToString());//操作工列表
        if (dtContainers == null || stepDatas == null || operatorDatas == null || dtContainers.Rows.Count == 0 || stepDatas.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "数据过期", Result = false }));
            return;
        }
        if (operatorDatas.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未选择操作工", Result = false }));
            return;
        }
        string teamId = context.Request.Form["teamId"].ToString();//班组
        string resource = context.Request.Form["resource"].ToString();//设备
        if (string.IsNullOrWhiteSpace(resource))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "请选择设备", Result = false }));
            return;
        }
        if (!bathResMonitorBusiness.IsVaildResMonitorCheck(resource))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "设备【" + context.Request.Form["resourceName"].ToString() + "】槽液化验到期，请重新提交检测", Result = false }));
            return;
        }
        string dispatchQty = context.Request.Form["dispatchQty"].ToString();//派工数量
        string startDate = context.Request.Form["startDate"].ToString();//开始日期
        string endDate = context.Request.Form["endDate"].ToString();//结束日期
        if (DateTime.Parse(startDate) < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "开始日期不能小于当前日期", Result = false }));
            return;
        }
        if (DateTime.Parse(startDate) > DateTime.Parse(endDate))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "开始日期不能大于结束日期", Result = false }));
            return;
        }
        string priorityCode = context.Request.Form["priorityCode"].ToString();//优先级编号
        string currStepId = dtContainers.Rows[0]["WORKFLOWSTEPID"].ToString();//当前工序
        int disPatchType = 1;
        foreach (DataRow step in stepDatas.Rows)
        {
            if (step["WORKFLOWSTEPID"].ToString() == currStepId)
            {
                disPatchType = 2;
                break;
            }
        }
        string strnull = "";
        bool isError = false;
        string msg = "派工成功";
        DataTable dtWorkSteP = GetWorkflowDT(ref strnull, m_UserInfo, dtContainers);
        foreach (DataRow dw in dtWorkSteP.Rows)
        {
            if (isError) { break; }
            foreach (DataRow ds in stepDatas.Rows)
            {
                if (ds["WORKFLOWSTEPID"].ToString() == dw["WORKFLOWSTEPID"].ToString())
                {
                    if (Convert.ToInt32(dispatchQty) > Convert.ToInt32(dw["CanDispatchQty"].ToString()))
                    {
                        isError = true;
                        msg = "派工数量大于可派数量或可派数已改变，请重新填写或者刷新页面";
                        break;
                    }
                }
            }
        }
        List<object[]> sqlStringList = new List<object[]>();
        DataTable dtSelect = new DataTable();
        dtSelect.Columns.Add("ContainerStepDispatchID");
        dtSelect.Columns.Add("WorkerID");
        List<ContainerStepDispatchDTO> dtoList = new List<ContainerStepDispatchDTO>();
        List<Dictionary<string, object>> containerStepDispatchList = new List<Dictionary<string, object>>(); //add by longb 2022-12-07
        if (!isError) //验证没问题，则派工
        {
            for (int i = 0; i < dtContainers.Rows.Count; i++)
            {
                string strContainerId = dtContainers.Rows[i]["CONTAINERID"].ToString();
                foreach (DataRow ds in stepDatas.Rows)
                {
                    ContainerStepDispatchDTO newDTO = new ContainerStepDispatchDTO();
                    newDTO.ContainerID = strContainerId;
                    newDTO.FactoryID = m_UserInfo.FactoryID;
                    newDTO.WorkCenterID = m_UserInfo.WorkCenterID;
                    newDTO.TeamID = teamId;
                    newDTO.WorkflowstepID = ds["WORKFLOWSTEPID"].ToString();
                    newDTO.ResourceID = resource;
                    newDTO.Qty = Convert.ToInt32(dispatchQty);//派工数量
                    newDTO.PlannedStartDate = Convert.ToDateTime(startDate);
                    newDTO.PlannedFinishDate = Convert.ToDateTime(endDate);
                    newDTO.ContainerStepDispatchID = Guid.NewGuid().ToString();
                    newDTO.EmployeeID = m_UserInfo.EmployeeID.ToString();
                    newDTO.PriorityCode = int.Parse(priorityCode);
                    newDTO.WorkerID = operatorDatas.Rows.Count > 1 ? "" : operatorDatas.Rows[0]["EMPLOYEEID"].ToString();
                    //如果不存在相同的批次、工序，则添加派工
                    if (dtoList.Where(p => p.ContainerID == newDTO.ContainerID && p.WorkflowstepID == newDTO.WorkflowstepID).Count() == 0)
                    {
                        dtoList.Add(newDTO);
                        sqlStringList.Add(uMESDispatchbusiness.FillContainerStepDispatchInfo(newDTO));
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("parentid", newDTO.ContainerStepDispatchID);
                        dic.Add("sendtype", "1");//派工--发送热表
                        containerStepDispatchList.Add(dic);//add by longb 2022-12-07
                        if (operatorDatas.Rows.Count > 1)
                        {
                            foreach (DataRow item in operatorDatas.Rows)
                            {
                                sqlStringList.Add(uMESDispatchbusiness.FillDispatchdetails(newDTO.ContainerStepDispatchID, item["EMPLOYEEID"].ToString()));
                            }
                        }
                    }
                }
                sqlStringList.Add(uMESDispatchbusiness.FillUpdateContainerDispatchNum(strContainerId, disPatchType.ToString()));
            }
        }
        if (sqlStringList.Count > 0)
        {
            if (!DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlStringList))
            {
                isError = true;
                msg = "更新批次派工状态出错";
            }
            else
            {
                //添加自检自分(如果当前序是专检序且派工数大于2，则自动首件报工)
                //if (isSelfCheck)
                //{
                //    dtoList = dtoList.Where(p => p.WorkflowstepID == currStepId).ToList();//筛选当前序的派工
                //    SetSelfCheckData(dtoList, operatorDatas.Rows[0]["EMPLOYEEID"].ToString());
                //}

                //add by longb 发送工控网使用
                if (context.Request.Form["btype"].ToString() == "3")
                {
                    InsertSendGKWData(containerStepDispatchList);
                }

                //派工后自动发起工装及辅料准备申请 add zhunan 2023.1.5
                uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
                string strAutoArrangement = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "派工后工装及辅料准备");
                if (strAutoArrangement == "是")
                {
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    para.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//申请人
                    para.Add("TeamID", teamId);//班组
                    para.Add("PlannedFinishDate", endDate);//派工结束日期
                    para.Add("arrangementsID2", Guid.NewGuid().ToString());//生产准备ID2，一次申请，所有数据保持一致
                    foreach (DataRow item in dtContainers.Rows)
                    {
                        ArrayList sqlArrangementStringList = new ArrayList();
                        string containerid = item["ContainerID"].ToString();
                        sqlArrangementStringList = uMESDispatchbusiness.SaveSpecArrangementsAfterDispatching(stepDatas, containerid, para);
                        if (sqlArrangementStringList.Count > 0)
                        {
                            DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlArrangementStringList);
                        }
                    }
                }

            }
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = msg, Result = !isError }));
    }

    /// <summary>
    /// 保存批量批次派工数据
    /// </summary>
    /// <param name="context"></param>
    private void SaveBatchDispatchData(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "缓存过期，请刷新后再试", Result = false }));
            return;
        }
        //bool isSelfCheck = uMESCommonbusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "自检自分") == "是" ? true : false;//获取分厂属性
        DataTable dtContainers = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["dtContainers"].ToString());//批次列表
        DataTable stepDatas = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["stepDatas"].ToString());//工序列表
        DataTable operatorDatas = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["operatorDatas"].ToString());//操作工列表
        if (dtContainers == null || stepDatas == null || operatorDatas == null || dtContainers.Rows.Count == 0 || stepDatas.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "数据过期", Result = false }));
            return;
        }
        if (operatorDatas.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未选择操作工", Result = false }));
            return;
        }
        string teamId = context.Request.Form["teamId"].ToString();//班组
        string resource = context.Request.Form["resource"].ToString();//设备
        if (string.IsNullOrWhiteSpace(resource))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "请选择设备", Result = false }));
            return;
        }
        if (!bathResMonitorBusiness.IsVaildResMonitorCheck(resource))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "设备【" + context.Request.Form["resourceName"].ToString() + "】槽液化验到期，请重新提交检测", Result = false }));
            return;
        }
        string startDate = context.Request.Form["startDate"].ToString();//开始日期
        string endDate = context.Request.Form["endDate"].ToString();//结束日期
        if (DateTime.Parse(startDate) < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "开始日期不能小于当前日期", Result = false }));
            return;
        }
        if (DateTime.Parse(startDate) > DateTime.Parse(endDate))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "开始日期不能大于结束日期", Result = false }));
            return;
        }
        string priorityCode = context.Request.Form["priorityCode"].ToString();//优先级编号
        string currStepId = dtContainers.Rows[0]["WORKFLOWSTEPID"].ToString();//当前工序
        int disPatchType = 1;
        foreach (DataRow step in stepDatas.Rows)
        {
            if (step["WORKFLOWSTEPID"].ToString() == currStepId)
            {
                disPatchType = 2;
                break;
            }
        }
        List<object[]> sqlStringList = new List<object[]>();
        DataTable dtSelect = new DataTable();
        dtSelect.Columns.Add("ContainerStepDispatchID");
        dtSelect.Columns.Add("WorkerID");
        string strnull = "";
        bool isError = false;
        string msg = "派工成功";
        List<ContainerStepDispatchDTO> dtoList = new List<ContainerStepDispatchDTO>();
        List<Dictionary<string, object>> containerStepDispatchList = new List<Dictionary<string, object>>(); //add by longb 2022-12-07
        for (int i = 0; i < dtContainers.Rows.Count; i++)
        {
            string strContainerId = dtContainers.Rows[i]["CONTAINERID"].ToString();
            strnull = "strnull";
            DataTable dt = dtContainers.Copy();
            dt.Rows.Clear();
            dt.ImportRow(dtContainers.Rows[i]);
            DataTable dtWorkSteP = GetWorkflowDT(ref strnull, m_UserInfo, dt);
            foreach (DataRow dw in dtWorkSteP.Rows)
            {
                foreach (DataRow ds in stepDatas.Rows)
                {
                    if (ds["WORKFLOWSTEPID"].ToString() == dw["WORKFLOWSTEPID"].ToString())
                    {
                        ContainerStepDispatchDTO newDTO = new ContainerStepDispatchDTO();
                        newDTO.ContainerID = strContainerId;
                        newDTO.FactoryID = m_UserInfo.FactoryID;
                        newDTO.WorkCenterID = m_UserInfo.WorkCenterID;
                        newDTO.TeamID = teamId;
                        newDTO.WorkflowstepID = ds["WORKFLOWSTEPID"].ToString();
                        newDTO.ResourceID = resource;
                        newDTO.Qty = Convert.ToInt32(dw["CanDispatchQty"].ToString());//派工数量取可派工数量
                        newDTO.PlannedStartDate = Convert.ToDateTime(startDate);//
                        newDTO.PlannedFinishDate = Convert.ToDateTime(endDate);//
                        newDTO.ContainerStepDispatchID = Guid.NewGuid().ToString();
                        newDTO.EmployeeID = m_UserInfo.EmployeeID.ToString();
                        newDTO.PriorityCode = int.Parse(priorityCode);
                        newDTO.WorkerID = operatorDatas.Rows.Count > 1 ? "" : operatorDatas.Rows[0]["EMPLOYEEID"].ToString();
                        if (dtoList.Where(p => p.ContainerID == newDTO.ContainerID && p.WorkflowstepID == newDTO.WorkflowstepID).Count() == 0)
                        {
                            dtoList.Add(newDTO);
                            sqlStringList.Add(uMESDispatchbusiness.FillContainerStepDispatchInfo(newDTO));
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("parentid", newDTO.ContainerStepDispatchID);
                            dic.Add("sendtype", "1");//派工--发送热表
                            containerStepDispatchList.Add(dic);//add by longb 2022-12-07
                            if (operatorDatas.Rows.Count > 1)
                            {
                                foreach (DataRow item in operatorDatas.Rows)
                                {
                                    sqlStringList.Add(uMESDispatchbusiness.FillDispatchdetails(newDTO.ContainerStepDispatchID, item["EMPLOYEEID"].ToString()));
                                }
                            }
                        }
                    }
                }
            }
            sqlStringList.Add(uMESDispatchbusiness.FillUpdateContainerDispatchNum(strContainerId, disPatchType.ToString()));
        }
        if (sqlStringList.Count > 0)
        {
            if (!DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlStringList))
            {
                isError = true;
                msg = "更新批次派工状态出错";
            }
            else
            {
                //添加自检自分(如果当前序是专检序且派工数大于2，则自动首件报工)
                //if (isSelfCheck)
                //{
                //    dtoList = dtoList.Where(p => p.WorkflowstepID == currStepId).ToList();//筛选当前序的派工
                //    SetSelfCheckData(dtoList, operatorDatas.Rows[0]["EMPLOYEEID"].ToString());
                //}

                //add by longb 发送工控网使用
                if (context.Request.Form["btype"].ToString() == "3")
                {
                    InsertSendGKWData(containerStepDispatchList);
                }

                //派工后自动发起工装及辅料准备申请 add zhunan 2023.1.5
                uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
                string strAutoArrangement = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "派工后工装及辅料准备");
                if (strAutoArrangement == "是")
                {
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    para.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//申请人
                    para.Add("TeamID", teamId);//班组
                    para.Add("PlannedFinishDate", endDate);//派工结束日期
                    para.Add("arrangementsID2", Guid.NewGuid().ToString());//生产准备ID2，一次申请，所有数据保持一致
                    foreach (DataRow item in dtContainers.Rows)
                    {
                        ArrayList sqlArrangementStringList = new ArrayList();
                        string containerid = item["ContainerID"].ToString();
                        sqlArrangementStringList = uMESDispatchbusiness.SaveSpecArrangementsAfterDispatching(stepDatas, containerid, para);
                        if (sqlArrangementStringList.Count > 0)
                        {
                            DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlArrangementStringList);
                        }
                    }
                }
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = msg, Result = !isError }));
    }

    /// <summary>
    /// 保存自检自分，专检序派工数量大于2自动首件报工
    /// </summary>
    /// <param name="dtoList"></param>
    /// <param name="workerID"></param>
    public void SetSelfCheckData(List<ContainerStepDispatchDTO> dtoList, string workerID)
    {
        List<object[]> sqlStringList = new List<object[]>();
        string containerids = "";
        foreach (ContainerStepDispatchDTO dto in dtoList)
        {
            List<object[]> sqlStringList1 = uMESDispatchbusiness.FillSelfCheckData(dto, workerID);
            if (sqlStringList1.Count > 0)
            {
                sqlStringList.AddRange(sqlStringList1);
                if (!containerids.Contains(dto.ContainerID))
                {
                    containerids += "'" + dto.ContainerID + "',";
                }
            }
        }
        if (sqlStringList.Count > 0)
        {
            DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlStringList);
            containerids = containerids.Trim(',');
            containerids = containerids.Trim('\'');
            m_ReportBusiness.UpdateWorkReportNum(containerids);//更新批次当前序的报工数
        }
    }

    public void InsertSendGKWData(List<Dictionary<string, object>> list)
    {
        var arrList = new ArrayList();
        foreach (var dic in list)
        {
            arrList.Add(string.Format("insert into Sendgkwdata(id,parentid,sendtype)values('{0}','{1}','{2}')", Guid.NewGuid().ToString(), dic["parentid"], dic["sendtype"]));
        }
        var result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlListTran(arrList);
    }

}